#!/usr/bin/bash

set -e

function report_error() {
	echo -ne "\033[1;31mError: \033[22m"
	echo $* >&2
	echo -ne "\033[0m"
}

function read_var(){
	echo -ne "\033[32m$1: \033[0m"
	read $2
}

function read_pass(){
	echo -ne "\033[32m$1: \033[0m"
	read -s $2
	echo
}

function assert_run_as_root(){
	uid=`id -u`
	if [ "$uid" != "0" ]; then
		report_error "Please run it as root or with sudo!"
		exit 1
	fi
}

function ask_for_db_info(){
	echo -e '\033[36;40m'
	echo "######################################################################"
	echo "#                                                                    #"
	echo "#             Please reply below questions CAREFULLY!                #"
	echo "#                                                                    #"
	echo -e "######################################################################\033[0m"
	echo 
	read_var "User name that you want to create" DB_USER
	read_var "Hostname for database user $DB_USER[Default: localhost]" DB_HOST
	while true; do
		read_pass "Password for database user $DB_USER" DB_PASSWORD
		if [ -z $DB_PASSWORD ]; then
			report_error "Password must not be empty! Please input again."
			continue
		fi
		read_pass "Password for database user $DB_USER again"
		if [ "x$REPLY" = "x$DB_PASSWORD" ]; then
			break
		else
			report_error "The two password you supplied is different. Please input again."
		fi
	done
	read_var "Databases you want to created by ${DB_USER}(separate by whitespace)" DATABASES
	DB_HOST=${DB_HOST:-localhost}
}

function confirm_db_info(){
	echo
	echo Will create database objects as below:
	echo =============================================
	echo -e "\tUser:\t\t ${DB_USER}@${DB_HOST}"
	idx=1
	for db in $DATABASES; do
		echo -e "\tDatabase $idx:\t\t $db"
		idx=$((idx+1))
	done
	echo =============================================

	PS3="Are you confirm it?"
	options=("Yes, just do it!" "No, I need modify it!" "Quit.")
	select opt in "${options[@]}"; do
		case $opt in
			"Yes, just do it!")
				return 0
				;;
			"No, I need modify it!")
				return 1
				return
				;;
			"Quit.")
				return 2
				;;
			*)
				report_error "Select Must In (1, 2, 3)"
				;;
		esac
	done
}

function create_user_and_db(){
	echo "CREATE USER IF NOT EXISTS '${DB_USER}'@'$DB_HOST' IDENTIFIED BY '$DB_PASSWORD';" | mysql
	for db in $DATABASES; do
		echo -e "CREATE DATABASE $db;\nGRANT ALL ON ${db}."'*'" TO '$DB_USER'@'$DB_HOST';" | mysql
	done
	echo "FLUSH PRIVILEGES;" | mysql
}

assert_run_as_root

while true; do
	ask_for_db_info
	confirm_db_info
	case $? in
		0)
			break
			;;
		1)
			continue
			;;
		2)
			exit 0
	esac
done


if create_user_and_db; then
	echo "Successed!"
fi
